//
//  MPHomeController.m
//  MarkPlatform
//
//  Created by xiao6 on 2017/12/17.
//  Copyright © 2017年 AT. All rights reserved.
//

#import "MPHomeController.h"
#import "MPTaskModel.h"
#import "MPTaskInfoView.h"
#import "MPMarkImageView.h"
#import "MBProgressHUD+MPSuccessGif.h"

@interface MPHomeScrollView : UIScrollView <UIGestureRecognizerDelegate>
@end
@implementation MPHomeScrollView
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([self.delegate respondsToSelector:@selector(gestureRecognizerShouldBegin:)]) {
        return [((id<UIGestureRecognizerDelegate>)(self.delegate)) gestureRecognizerShouldBegin:gestureRecognizer];
    }
    return YES;
}
@end

@interface MPHomeController () <UIGestureRecognizerDelegate> {
    
}
@property (nonatomic, strong) MPTaskModel *task;
@property (nonatomic, strong) MPMarkImageView *markView;
@property (nonatomic, strong) MPTaskInfoView *taskInfoView;
@property (nonatomic, strong) UIView *maskBar;
@property (nonatomic, weak) IBOutlet UIButton *repealButton;
@property (nonatomic, weak) IBOutlet UIButton *redoButton;
@property (nonatomic, weak) IBOutlet UIButton *maskButton;
@property (nonatomic, weak) IBOutlet UIButton *nextButton;
@property (nonatomic, weak) IBOutlet MPAppButton *submitButton;
@property (nonatomic, strong) UIView *checkBar;
@property (weak, nonatomic) IBOutlet MPAppButton *checkPassButton;
@property (weak, nonatomic) IBOutlet UIButton *checkNoPassButton;

@end

@implementation MPHomeController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showNavTitle:@"标注任务" backItem:YES];
    self.navigationItem.leftBarButtonItem = [self navItemWithImage:[UIImage imageNamed:@"nav_mine"] action:@selector(didClickLeftItem:)];
    [self setupViews];
    [self setupEmpty:self.scrollView];
    if ([ATLocal user].isLogin) {
        [self headerRefreshing];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRefreshing) name:ATUserLoginNotification object:nil];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)refreshData:(NSInteger)page {
    static NSInteger retryCount = 0;
    [MPHttpTool POST:[@"business/task/queryTask/" stringByAppendingString:SafeDicObj([ATLocal user].userId)]
              params:nil
             success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                 self.task = [MPTaskModel modelWithJSON:result.data];
                 [self updateDisplay];
                 [self endRefresh:NO];
                 retryCount = 0;
             } failure:^(NSString *errorMsg) {
                 retryCount++;
                 if (retryCount < 3) {
                     [self performSelector:@selector(headerRefreshing) withObject:nil afterDelay:1];
                 }
                 else {
                     [MBProgressHUD showMessage:errorMsg];
                     self.task = nil;
                     [self updateDisplay];
                     [self endRefresh:NO];
                 }
             }];
}

- (void)setTask:(MPTaskModel *)task {
    _task = task;
    
    [self setNavItemTitle:_task.taskTypeName ?: @"标注任务"];
    self.taskInfoView.model = _task;
    self.markView.model = _task;
    if (_task.way == MPMarkTypePoint) {
        [self.maskButton setImage:[UIImage imageNamed:@"toolbar_yuanxing_pre"] forState:UIControlStateHighlighted];
        [self.maskButton setImage:[UIImage imageNamed:@"toolbar_yuanxing_nor"] forState:UIControlStateNormal];
    }
    else {
        [self.maskButton setImage:[UIImage imageNamed:@"toolbar_juxing_pre"] forState:UIControlStateHighlighted];
        [self.maskButton setImage:[UIImage imageNamed:@"toolbar_juxing_nor"] forState:UIControlStateNormal];
    }
}

- (void)updateDisplay {
    self.markView.hidden = !self.task;
    self.taskInfoView.hidden = !self.task;
    self.maskBar.hidden = !self.task || self.task.type != MPTaskTypeMark;
    self.checkBar.hidden = !self.task || self.task.type != MPTaskTypeReview;
    self.markView.userInteractionEnabled = self.task.type == MPTaskTypeMark;
    
    if (!self.task) {
        return;
    }
    if (!self.maskBar.hidden) {
        self.repealButton.enabled = self.markView.steps.count > 0;
        self.redoButton.enabled = self.markView.nextSteps.count > 0;
        self.maskButton.selected = self.markView.steps.count > 0;
        self.submitButton.enabled = self.markView.steps.count > 0;
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    [self.markView addStepWithMark:nil];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.markView addStepWithMark:nil];
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.numberOfTouches > 1) {
        return YES;
    }
    CGRect rect = self.markView.steps.lastObject.markModels.firstObject.viewRect;
    rect = CGRectInset(rect, -15, -15);
    return !CGRectContainsPoint(rect, [gestureRecognizer locationInView:self.markView]);
}

#pragma mark - action
- (IBAction)clickRepeal:(id)sender {
    [self.markView preStep];
    [self updateDisplay];
}
- (IBAction)clickRedo:(id)sender {
    [self.markView nextStep];
    [self updateDisplay];
}
- (IBAction)clickMask:(id)sender {// 标注或重置
    if (self.maskButton.isSelected) {
        [self.markView clearStep];
    }
    else {
        MPMarkModel *markModel;
        if (self.task.way == MPMarkTypeRect) {
            CGRect rect = CGRectZero;
            rect.origin = CGPointMake(self.markView.width / 2, self.markView.height / 2);
            rect = CGRectInset(rect, -40, -40);
            markModel = [MPMarkModel modelWithRect:rect];
        }
        else {
            markModel = [MPMarkModel modelWithPoint:CGPointMake(self.markView.width / 2, self.markView.height / 2)];
        }
        [self.markView addStepWithMark:markModel];
    }
}
- (IBAction)clickNext:(id)sender {
    [self headerRefreshing];
}
- (IBAction)clickSubmit:(id)sender {
    [MBProgressHUD showWithCompletion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:@"business/task/tagging"
                  params:@{@"userID" : SafeDicObj([ATLocal user].userId),
                           @"taskID":self.task.Id,
                           @"coordinate":self.markView.stepCoordinate}
                 success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                     [hud hideWithSuccessGif:^{
                         [self headerRefreshing];
                     }];
                 } failure:ATHttpFailureWithHud(hud)];
    }];
}
- (IBAction)checkPass:(id)sender {
    [self checkTaskWithPass:YES];
}
- (IBAction)checkNoPass:(id)sender {
    [self checkTaskWithPass:NO];
}

- (void)checkTaskWithPass:(BOOL)isPass {
    [MBProgressHUD showWithCompletion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:@"business/task/audit"
                  params:@{@"userID" : SafeDicObj([ATLocal user].userId),
                           @"taskID":SafeDicObj(self.task.Id),
                           @"result":isPass ? @1 : @2}// 1通过 2不通过
                 success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                     [hud hideWithSuccess:nil completion:^{
                         [self headerRefreshing];
                     }];
                 } failure:ATHttpFailureWithHud(hud)];
    }];
}

#pragma mark - setupViews
- (void)setupViews {
    self.view.backgroundColor = [UIColor colorWithRGB:0xFAFAFA];
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.scrollView.minimumZoomScale = 1.0f;
    self.scrollView.maximumZoomScale = 4.0f;
    self.scrollView.bounces = YES;
    self.scrollView.bouncesZoom = YES;
    self.scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
    
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.superview).offset(NAVI_HIGHT);
        make.left.right.equalTo(self.scrollView.superview);
        make.bottom.equalTo(self.scrollView.superview).offset(-TAB_BAR_HIGHT);
    }];
    
    self.markView.scrollView = self.scrollView;
    self.markView.maxSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HIGHT - TAB_BAR_HIGHT);
    [self.scrollView addSubview:self.markView];
    [self.markView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.markView.superview);
    }];
    
    [self.view addSubview:self.taskInfoView];
    [self.taskInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(NAVI_HIGHT));
        make.left.right.offset(0);
    }];
    
    [self.view addSubview:self.maskBar];
    [self.maskBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
        make.height.equalTo(@(TAB_BAR_HIGHT));
    }];
    
    [self.maskButton setImage:[UIImage imageNamed:@"toolbar_chongzhi_pre"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [self.maskButton setImage:[UIImage imageNamed:@"toolbar_chongzhi_nor"] forState:UIControlStateSelected];
    [self.view addSubview:self.checkBar];
    [self.checkBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
        make.height.equalTo(@(TAB_BAR_HIGHT));
    }];
    
    @weakify(self)
    self.markView.notifyUpdateDisplay = ^(MPMarkImageView *markView) {
        @strongify(self)
        [self updateDisplay];
    };
    
    [self updateDisplay];
}

#pragma mark - delegate
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return self.task == nil;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.markView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    scrollView.yy_insetB = self.markView.top * 2;
    scrollView.yy_insetR = self.markView.left * 2;
}

#pragma mark - actions
- (void)didClickLeftItem:(id)sender {
    [self.frostedViewController presentMenuViewController];
}

#pragma mark - getter
- (MPMarkImageView *)markView {
    if (!_markView) {
        _markView = [[MPMarkImageView alloc] init];
    }
    return _markView;
}
- (MPTaskInfoView *)taskInfoView {
    if (!_taskInfoView) {
        _taskInfoView = [MPTaskInfoView instanceView];
    }
    return _taskInfoView;
}
- (UIView *)maskBar {
    if (!_maskBar) {
        _maskBar = [[NSBundle mainBundle] loadNibNamed:@"MPTaskMaskBar" owner:self options:nil][0];
    }
    return _maskBar;
}
- (UIView *)checkBar {
    if (!_checkBar) {
        _checkBar = [[NSBundle mainBundle] loadNibNamed:@"MPTaskCheckBar" owner:self options:nil][0];
    }
    return _checkBar;
}
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[MPHomeScrollView alloc] init];
        _scrollView.delegate = self;
    }
    return _scrollView;
}
@end
